package com.iwhalecloud.bss.kite.cucc.service.pos.bcmc.handler.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.iwhalecloud.bss.kite.common.constant.ServiceOfferConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteObjectUtils;
import com.iwhalecloud.bss.kite.common.util.SeqUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.reception.ICustReceptionService;
import com.iwhalecloud.bss.kite.cucc.client.dto.cust.CuccContextCustDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.KiteCustomerInfoReq;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosUserDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.scene.CuccCustInfoDTO;
import com.iwhalecloud.bss.kite.cucc.service.attr.LocalQuerySeqHelper;
import com.iwhalecloud.bss.kite.cucc.service.pos.bcmc.BcmcPosContext;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;

/**
 * <Description> <br>
 * 组装报文用户信息节点
 * 
 * @author XXZ<br>
 * @version 1.0<br>
 * @taskId <br>
 * @CreateDate 2020年12月15日 <br>
 * @since R9.0<br>
 * @see com.iwhalecloud.bss.kite.cucc.service.pos.bcmc.handler.impl <br>
 */
@Service
public class BcmcPosUserHandler extends AbstractBcmcPosHandler {

    @Autowired
    private ICustReceptionService custReceptionService;

    @SuppressWarnings("unchecked")
    @Override
    public void doHandle(BcmcPosContext context) {
        IQuerySceneInstService querySceneInstService = (IQuerySceneInstService) SpringUtil
            .getBean(IQuerySceneInstService.class);
        List<KitePosUserDTO> users = (List<KitePosUserDTO>) querySceneInstService
            .getExtParameterValue(context.getSceneInstId(), "serialNumber");
        KiteSceneInst kiteSceneInst = querySceneInstService.getSceneInst(context.getSceneInstId());

        if (KiteListUtils.isEmpty(users)) {
            users = Lists.newArrayList();
            KitePosUserDTO user = new KitePosUserDTO();
            user.setUserId(getUserId(context.getSceneInstId(), context.getCustDto()));
            user.setSerialNumber(querySceneInstService.getCommonAttrValue(context.getSceneInstId(), "business_number"));
            user.setName(querySceneInstService.getCommonAttrValue(context.getSceneInstId(), "group_user_name"));
            user.setProvinceCode(context.getCustDto().getProvinceCode());
            user.setCityCode(context.getCustDto().getEparchyCode());
            user.setDistrictCode(context.getCustDto().getRegionId());
            user.setInstanceId(SeqUtils.getNext("SEQ_USER_ID"));
            users.add(user);
            context.getPosDto().setUsers(users);
        }
        else {
            String serviceOfferId = (String) Optional
                .ofNullable(querySceneInstService.getSceneInst(context.getSceneInstId()))
                .map(KiteSceneInst::getServiceOfferId).orElse("");
            users.forEach(user -> {
                // 非二次业务需要生成实例ID
                if ("1013".equals(serviceOfferId) || "1001".equals(serviceOfferId)) {
                    user.setInstanceId(SeqUtils.getNext("SEQ_USER_ID"));

                    user.setCityCode(context.getCustDto().getLanId());
                    user.setProvinceCode(context.getCustDto().getProvinceCode());
                }
                if (ServiceOfferConsts.SERVICE_OFFER_TRANSFER.equals(kiteSceneInst.getServiceOfferId())) {
                    // 过户业务客户信息需要重新调整
                    String newCustId = kiteSceneInst.getNewCustId();
                    String sceneInstId = context.getSceneInstId();
                    // 从缓存里面取
                    Map<String, Object> extParameter = querySceneInstService.getExtParameter(sceneInstId);
                    Object newCust = extParameter.get(sceneInstId + "_transNewCustDTO");
                    CuccCustInfoDTO newCustDto = Objects.nonNull(newCust) ? (CuccCustInfoDTO) newCust
                        : queryNewCustInfo(newCustId);
                    user.setUseCustInstId(newCustId);
                    user.setProvinceCode(newCustDto.getProvinceCode());
                    user.setCityCode(newCustDto.getEparchyCode());
                    user.setName(newCustDto.getCustName());
                }
            });
            context.getPosDto().setUsers(users);
        }
    }

    private String getUserId(String sceneInstId, CuccContextCustDTO custDTO) {
        Map<String, String> inParam = new HashMap<>();
        inParam.put("SEQ_TYPE", "USER_ID");
        inParam.put("SYS_TYPE", "1");
        inParam.put("SYS_SOURCE", "");
        return LocalQuerySeqHelper.getSeqBySeqType(inParam, sceneInstId, custDTO);
    }

    @SuppressWarnings("deprecation")
    private CuccCustInfoDTO queryNewCustInfo(String custId) {
        KiteCustomerInfoReq kiteCustomerInfoReq = new KiteCustomerInfoReq();
        CuccCustInfoDTO cuccCustInfoDTO = new CuccCustInfoDTO();
        kiteCustomerInfoReq.setCustId(custId);
        String staffCode = ContextUtil.getSimpleLoginInfo().getStaffCode();
        String eparchyCode = ContextUtil.getSimpleLoginInfo().getLanId();
        String provinceCode = ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr();
        kiteCustomerInfoReq.setStaffCode(staffCode);
        kiteCustomerInfoReq.setEparchyCode(eparchyCode);
        kiteCustomerInfoReq.setProvinceCode(provinceCode);
        kiteCustomerInfoReq.setPageNum(1);
        kiteCustomerInfoReq.setPageSize(10);
        // 调用查询客户列表
        PageInfo<CuccCustInfoDTO> list = custReceptionService.customerListQuery(kiteCustomerInfoReq);
        if (!KiteObjectUtils.isEmpty(list) && KiteListUtils.isNotEmpty(list.getList())) {
            List<CuccCustInfoDTO> cuccCustInfoDTOList = list.getList();
            cuccCustInfoDTO = cuccCustInfoDTOList.get(0);
        }
        return cuccCustInfoDTO;
    }
}
